from itertools import count, islice, takewhile

import webapp2
from google.appengine.api import users, search
from util.webapp import ShopkeepApplication, ShopkeepHandler
from models.Item import Item, STATUS_ACTIVE

class SearchPage(ShopkeepHandler):
	def get(self):
		user = users.get_current_user()
		search_terms = self.request.GET.get("search_terms", "")
		sort_by_field = self.request.GET.get("sort_by_field", "")
		sort_direction = self.request.GET.get("sort_direction", "desc")
		cursor = self.request.GET.get("cursor")
		limit = min(100, int(self.request.GET.get("limit", 50)))
		next = []
		prev = []

		if search_terms:
			cursor = search.Cursor(cursor)
			if sort_by_field:
				if sort_direction == "desc":
					sort_by = [(sort_by_field, Item.DESCENDING)]
				else:
					sort_by = [(sort_by_field, Item.ASCENDING)]
			else:
				sort_by = []
			searchres = Item.search(search_terms, cursor, sort_by)
			results = []
			for doc in searchres:
				for field in doc.fields:
					if field.name == 'id':
						results.append(Item.get_by_id(int(field.value)))
						break
			# somehow figure out how to get total count here so we can figure out how much further we can advance with prev and next
		else:
			cursor = int(cursor if cursor else 0)
			query = Item.all()
			query.filter('status =', STATUS_ACTIVE)
			count = query.count()
			if sort_by_field:
				if sort_direction == "desc":
					query.order("-" + sort_by_field)
				else:
					query.order(sort_by_field)
			results = query.run(offset=cursor, limit=limit)
			prev = range(0, cursor, limit)[-5:]
			next = range(cursor + limit, min(count, cursor + limit * (10 - len(prev))), limit)

		data = {
			"items": results,
			"cursor": cursor,
			"next": next,
			"prev": prev,
			"search_terms": search_terms,
			"sort_by_field": sort_by_field,
			"sort_direction": sort_direction
		}

		self.render_response("search.html", data)

app = ShopkeepApplication([
	('/', SearchPage),
	('/search', SearchPage)
])
